package org.aeon.colorfulplanebattle.view.components;

import org.aeon.colorfulplanebattle.flying.entity.Plane;
import org.aeon.colorfulplanebattle.view.GameState;

import javax.swing.*;
import java.awt.*;
import java.util.Objects;

import static org.aeon.colorfulplanebattle.constant.GameBasisConstant.BLOOD_HEIGHT;
import static org.aeon.colorfulplanebattle.constant.GameBasisConstant.BLOOD_WIDTH;

/**
 * @author: MissingAeon
 * @date: 2024/1/8 19:39
 * @description:
 */
public class BloodBar extends JComponent {
    private static final Image healthy; // 健康的
    private static final Image damaged; // 受损的

    static {
        healthy = new ImageIcon(Objects.requireNonNull(BloodBar.class.getClassLoader().getResource("img/qita/xiai_red.png"))).getImage();
        damaged = new ImageIcon(Objects.requireNonNull(BloodBar.class.getClassLoader().getResource("img/qita/xiai_ash.png"))).getImage();
    }

    private final GameState gameState;
    private Plane myPlane;

    public BloodBar(GameState gameState) {
        this.gameState = gameState;
        // 绝对定位
        this.setBounds(5, 5, BLOOD_WIDTH * 10, BLOOD_HEIGHT * 2 + 5);
        gameState.put("BloodBarReset", (Runnable) this::reset);
    }

    private void painting(Graphics g, Image picture, int i, int j) {
        g.drawImage(picture, BLOOD_WIDTH * i, BLOOD_HEIGHT * j, BLOOD_WIDTH, BLOOD_HEIGHT, this);
    }

    @Override
    public void paintComponent(Graphics g) {
        if (myPlane != null) {
            // 绘制图像
            int i, j;
            for (i = j = 0; i < getMaxHp(); i++, j = i / 10) {
                painting(g, getHp() > i ? healthy : damaged, i - 10 * j, j);
            }
        }

    }


    private int getHp() {
        return myPlane.getHp();
    }

    private int getMaxHp() {
        return myPlane.getMaxHp();
    }

    private void reset() {
        if (this.gameState.exist("myPlane")) {
            myPlane = this.gameState.get("myPlane");
        }
    }
}
